package zcw.com.lib_leet_code;

import java.util.HashMap;
import java.util.Map;

import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/8.<br><br>
 *
 * 两数之和 II - 输入有序数组
 */
public class Topic167 {
    public static void main(String[] args) {
        Topic167 instance = new Topic167();

        int[] array = new int[] {2,7,11,15};
        Util.printArray(instance.twoSum(array, 9));

        array = new int[] {2,3,4};
        Util.printArray(instance.twoSum(array, 6));

        array = new int[] {-1,0};
        Util.printArray(instance.twoSum(array, -1));
    }

    public int[] twoSum(int[] numbers, int target) {
        int[] result = {-1, -1};

        int low = 0;
        int high = numbers.length - 1;

        while (low < high) {
            int sum = numbers[low] + numbers[high];

            if(sum == target) {
                result[0] = low + 1;
                result[1] = high + 1;
                break;
            }

            if(sum < target) {
                low++;
            }
            else {
                high--;
            }
        }

        return result;
    }

    public int[] twoSum2(int[] numbers, int target) {
        int[] result = {-1, -1};

        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < numbers.length; i++) {
            if(map.containsKey(target - numbers[i])) {
                result[0] = map.get(target - numbers[i]) + 1;
                result[1] = i + 1;
                break;
            }

            map.put(numbers[i], i);
        }

        return result;
    }
}
